<template>
  <div class="app-container">
    <el-form ref="knowledgeForm" :model="knowledgeForm" :rules="knowledgeFormRules" label-width="80px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="所属分类" prop="type">
            <el-select v-model="knowledgeForm.type" clearable placeholder="请选择所属分类">
              <el-option
                v-for="type in typeOptions"
                :key="type.dictValue"
                :value="type.dictValue"
                :label="type.dictLabel"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否公开" prop="isPublic">
            <el-switch v-model="knowledgeForm.isPublic"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="knowledgeForm.title" clearable placeholder="请填写标题" maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="关键字" prop="keywords">
            <el-input v-model="knowledgeForm.keywords" clearable placeholder="请填写关键字" maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="内容" prop="keywords">
            <div style="border: 1px solid #ccc;"> <!-- 这里必须加v-if=showDialog，让wangEditor随dialog关闭而销毁；否则再次打开可能会报错“Cannot find a descendant at path [3] in node” -->
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="wangEditor.editor"
                :defaultConfig="wangEditor.toolbarConfig"
                :mode="wangEditor.mode"
              />
              <Editor
                style="height: 400px; overflow-y: hidden;"
                v-model="wangEditor.html"
                :defaultConfig="wangEditor.editorConfig"
                :mode="wangEditor.mode"
                @onCreated="onEditorCreated"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="附件" prop="attach">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            :on-remove="handleRemove"
            :on-change="handleChange"
            :http-request="handleUpload"
            :file-list="attachFileList"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: right; margin-right: 70px">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import "@wangeditor/editor/dist/css/style.css"
import { insertKnowledge, selectKnowledgeById, updateKnowledge, uploadAttachFile } from '@/api/knowledge/knowledge'
import { getToken } from '@/utils/auth'

export default {
  name: 'manage',
  components: {
    Editor,
    Toolbar
  },
  data() {
    return {
      // 是否正在编辑
      editing: false,
      // 表单
      knowledgeForm: {
        id: '',
        type: '',
        title: '',
        keywords: '',
        isPublic: true,
        content: '',
        attachList: []
      },
      // 表单数据校验
      knowledgeFormRules: {
        type: [
          { required: true, message: "所属分类必须选择", trigger: ['blur', 'change'] }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: ['blur', 'change'] }
        ],
        keywords: [
          { required: true, message: "关键字不能为空", trigger: ['blur', 'change'] }
        ]
      },
      // 所属分类选项
      typeOptions: [],
      // 富文本编辑器配置信息
      wangEditor: {
        editor: null,
        html: '',
        toolbarConfig: {
          excludeKeys: [
            'insertImage',
            'insertVideo',
            'fullScreen'
          ]
        },
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF: {
            uploadImage: {
              server: process.env.VUE_APP_BASE_API + '/knowledge/uploadFile',
              fieldName: 'file',
              maxFileSize: 10 * 1024 * 1024,
              maxNumberOfFiles: 10,
              headers: {
                Accept: 'application/json;charset=UTF-8',
                Authorization: getToken()
              },
              withCredentials: true,
              timeout: 10 * 1000,
              onBeforeUpload(files){
                Message({
                  message: '图片正在上传中,请耐心等待',
                  duration: 0,
                  customClass: 'uploadTip',
                  iconClass: 'el-icon-loading',
                  showClose: true
                });
                return files;
              },
              onDelete(file){
                console.log('dsdsdsdsdsds')
              },
              // 自定义插入图片
              customInsert(res, insertFn) {
                console.log('res = ' + JSON.stringify(res))
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的Message
                Message.closeAll();
                if (res.code === 200) {
                  Message.success({
                    message: `${res.data.originalName} 上传成功`
                  });
                } else {
                  Message.error({
                    message: `${res.data.originalName} 上传失败，请重新尝试`
                  });
                }
                insertFn(res.data.link, res.data.name, res.data.link);
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res);
                Message.closeAll();
                Message.error({
                  message: `${file.name} 上传出错`
                });
              }
            },
            uploadVideo: {
              server: process.env.VUE_APP_BASE_API + '/knowledge/uploadFile',
              fieldName: 'file',
              maxFileSize: 50 * 1024 * 1024,
              maxNumberOfFiles: 3,
              headers: {
                Accept: 'application/json;charset=UTF-8',
                Authorization: getToken()
              },
              withCredentials: true,
              timeout: 1000 * 1000,
              onBeforeUpload(files){
                Message({
                  message: '视频正在上传中,请耐心等待',
                  duration: 0,
                  customClass: 'uploadTip',
                  iconClass: 'el-icon-loading',
                  showClose: true
                });
                return files;
              },
              // 自定义插入视频
              customInsert(res, insertFn) {
                console.log('res = ' + JSON.stringify(res))
                // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
                // 先关闭等待的Message
                Message.closeAll();
                if (res.code === 200) {
                  Message.success({
                    message: `${res.data.originalName} 上传成功`
                  });
                } else {
                  Message.error({
                    message: `${res.data.originalName} 上传失败，请重新尝试`
                  });
                }
                insertFn(res.data.link, res.data.name, res.data.link);
              },
              // 单个文件上传成功之后
              onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res);
              },

              // 单个文件上传失败
              onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res);
              },

              // 上传进度的回调函数
              onProgress(progress) {
                console.log('progress', progress);
                // progress 是 0-100 的数字
              },

              // 上传错误，或者触发 timeout 超时
              onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res);
                Message.closeAll();
                Message.error({
                  message: `${file.name} 上传出错`
                });
              }
            }
          }
        },
        mode: 'default'
      },
      // 附件列表
      attachFileList: [],
    }
  },
  activated() {
    this.knowledgeForm.id =this.$route.query.id
    if(this.knowledgeForm.id != null && this.knowledgeForm.id != undefined) {
      selectKnowledgeById(this.knowledgeForm.id).then(response => {
        console.log('s = ' + JSON.stringify(response.data))
        this.knowledgeForm = response.data
        if (this.knowledgeForm.isPublic === '1') {
          this.knowledgeForm.isPublic = true
        } else {
          this.knowledgeForm.isPublic = false
        }
        this.wangEditor.html = this.knowledgeForm.content
        this.attachFileList = []
        if (response.data.attachList != null && response.data.attachList.length > 0) {
          response.data.attachList.forEach(f => {
            let a = {}
            a.name = f.fileName
            a.url = f.url
            this.attachFileList.push(a)
          })
        }
        this.showDialog = true
      })
    }
  },
  created() {
    this.getDicts("knowledge_type").then(response => {
      this.typeOptions = response.data;
    })
  },
  methods: {
    onEditorCreated(editor){
      this.wangEditor.editor = Object.seal(editor)
    },
    setEditorReadOnly(editor){
      this.wangEditor.editor = Object.seal(editor)
      this.wangEditor.editor.disable()
    },
    handleRemove(file, fileList) {
      var index = this.attachFileList.findIndex(f => f.name === file.name)
      this.attachFileList.splice(index, 1)

      var index2 = this.knowledgeForm.attachList.findIndex(f => f.fileName === file.name)
      this.knowledgeForm.attachList.splice(index2, 1)
    },
    handleChange(file, fileList) {
      this.attachFileList.push(file)
    },
    handleUpload(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      uploadAttachFile(formData).then(response => {
        let attach = {}
        attach.name = response.data.originalName
        attach.url = response.data.link
        this.attachFileList.push(attach)
        console.log('ss = ' + JSON.stringify(this.attachFileList))
        this.$message.success('附件上传成功！')
      })
    },
    submitForm(){
      if(this.wangEditor.editor.getHtml() === '') {
        this.$message.warning('请填写内容！')
        return
      }
      const formData = new FormData()
      formData.append('id', this.knowledgeForm.id)
      formData.append('type', this.knowledgeForm.type)
      formData.append('title', this.knowledgeForm.title)
      formData.append('keywords', this.knowledgeForm.keywords)
      formData.append('isPublic', this.knowledgeForm.isPublic ? '1' : '0')
      formData.append('content', this.wangEditor.editor.getHtml())
      if(this.knowledgeForm.attachList != null && this.knowledgeForm.attachList.length > 0){
        this.knowledgeForm.attachList.forEach((item, index) => {
          formData.append('attachList['+index+'].id', item.id)
          formData.append('attachList['+index+'].knowlegeId', item.knowlegeId)
          formData.append('attachList['+index+'].fileName', item.fileName)
          formData.append('attachList['+index+'].url', item.url)
        })
      }

      if(this.attachFileList.length > 0){
        this.attachFileList.forEach(a => {
          if(a.raw != null && a.raw != undefined){
            formData.append('files', a.raw)
          }
        })
      }

      this.$refs.knowledgeForm.validate(valid => {
        if(valid) {
          if(this.knowledgeForm.id == undefined || this.knowledgeForm.id == null || this.knowledgeForm.id == '') {
            insertKnowledge(formData).then(response => {
              this.$message.success('新增成功！')
              this.resetKnowlegeForm()
              this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
              this.$router.replace({ path: "/zsk/knowledge/index" }); // 要打开的页面
            })
          } else {
            updateKnowledge(formData).then(response => {
              this.$message.success('修改成功！')
              this.resetKnowlegeForm()
              this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
              this.$router.replace({ path: "/zsk/knowledge/index" }); // 要打开的页面
            })
          }
        }
      })
    },
    cancel(){
      this.resetKnowlegeForm()
      this.$store.dispatch("tagsView/delView", this.$route); //关闭当前页
      this.$router.replace({ path: "/zsk/knowledge/index" }); // 要打开的页面
    },
    resetKnowlegeForm() {
      this.knowledgeForm = {
        id: '',
        type: '',
        title: '',
        keywords: '',
        content: '',
      }
      this.resetForm('knowledgeForm')
      this.wangEditor.html= ''
      this.attachFileList = []
    }
  },
  beforeDestroy() {
    // if(this.editing){
    //   this.$confirm('有未保存的更改，是否确认关闭？', '提醒', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消'
    //   }).then(()=>{
    //
    //   })
    // }
    const editor = this.wangEditor.editor
    if(editor == null) return
    editor.destroy()
  },
  watch: {
    'knowledgeForm.type': {
      handler(newValue, oldValue) {
        console.log('form.type')
        this.editing = true
      },
      immediate: false
    },
    'knowledgeForm.title': {
      handler(newValue, oldValue) {
        console.log('form.title')
        this.editing = true
      },
      immediate: false
    },
    'knowledgeForm.keywords': {
      handler(newValue, oldValue) {
        console.log('form.keywords')
        this.editing = true
      },
      immediate: false
    },
    'wangEditor.html': {
      handler(newValue, oldValue) {
        console.log('form.content')
        this.editing = true
      },
      immediate: false
    }
  }
}
</script>

<style scoped lang="scss">

</style>
